class EnhancedWordSegmenter {
  constructor() {
    // 初始化空词典
    this.dictionary = new Set();
    // 最大匹配长度
    this.maxWordLength = 6;
    // 已加载的词库
    this.loadedDictionaries = [];
  }
  
  /**
   * 从数组加载词库
   * @param {string[]} dictionary 词库数组
   * @param {string} name 词库名称（可选）
   */
  loadDictionary(dictionary, name = 'default') {
    if (!Array.isArray(dictionary)) {
      throw new Error('词库必须是数组类型');
    }
    
    // 添加所有词汇到词典
    dictionary.forEach(word => {
      if (typeof word === 'string' && word.length > 0) {
        this.dictionary.add(word);
      }
    });
    
    this.loadedDictionaries.push(name);
    console.log(`已加载词库: ${name}，包含 ${dictionary.length} 个词汇`);
    return this;
  }
  
  /**
   * 从URL加载词库（适用于浏览器环境）
   * @param {string} url 词库JSON文件URL
   * @param {string} name 词库名称
   * @returns {Promise}
   */
  loadDictionaryFromURL(url, name) {
    if (typeof fetch !== 'function') {
      return Promise.reject(new Error('当前环境不支持fetch API'));
    }
    
    return fetch(url)
      .then(response => {
        if (!response.ok) {
          throw new Error(`加载词库失败: ${response.statusText}`);
        }
        return response.json();
      })
      .then(dictionary => {
        this.loadDictionary(dictionary, name || url);
        return this;
      });
  }
  
  /**
   * 添加词汇到词典
   * @param {string|string[]} words 要添加的词汇或词汇数组
   */
  addWords(words) {
    if (Array.isArray(words)) {
      words.forEach(word => this.dictionary.add(word));
    } else {
      this.dictionary.add(words);
    }
    return this;
  }
  
  /**
   * 从词典中移除词汇
   * @param {string|string[]} words 要移除的词汇或词汇数组
   */
  removeWords(words) {
    if (Array.isArray(words)) {
      words.forEach(word => this.dictionary.delete(word));
    } else {
      this.dictionary.delete(words);
    }
    return this;
  }
  
  /**
   * 检查词是否在词典中
   * @param {string} word 要检查的词
   * @returns {boolean}
   */
  hasWord(word) {
    return this.dictionary.has(word);
  }
  
  /**
   * 获取已加载的词库信息
   * @returns {string[]} 已加载词库名称数组
   */
  getLoadedDictionaries() {
    return [...this.loadedDictionaries];
  }
  
  /**
   * 获取词典大小
   * @returns {number} 词典中词汇数量
   */
  getDictionarySize() {
    return this.dictionary.size;
  }
  
  /**
   * 正向最大匹配分词算法
   * @param {string} text 要分词的文本
   * @returns {string[]} 分词结果数组
   */
  segmentForward(text) {
    const result = [];
    let index = 0;
    const textLength = text.length;
    
    while (index < textLength) {
      // 确定当前尝试的最大长度
      let maxTryLength = Math.min(this.maxWordLength, textLength - index);
      let found = false;
      
      // 从最大长度开始尝试匹配
      for (let len = maxTryLength; len > 0; len--) {
        const word = text.substr(index, len);
        if (this.dictionary.has(word)) {
          result.push(word);
          index += len;
          found = true;
          break;
        }
      }
      
      // 如果没有找到匹配的词，将单个字符作为词
      if (!found) {
        result.push(text.substr(index, 1));
        index++;
      }
    }
    
    return result;
  }
  
  /**
   * 反向最大匹配分词算法
   * @param {string} text 要分词的文本
   * @returns {string[]} 分词结果数组
   */
  segmentBackward(text) {
    const result = [];
    let index = text.length;
    
    while (index > 0) {
      // 确定当前尝试的最大长度
      let maxTryLength = Math.min(this.maxWordLength, index);
      let found = false;
      
      // 从最大长度开始尝试匹配
      for (let len = maxTryLength; len > 0; len--) {
        const start = index - len;
        const word = text.substr(start, len);
        if (this.dictionary.has(word)) {
          result.unshift(word);
          index = start;
          found = true;
          break;
        }
      }
      
      // 如果没有找到匹配的词，将单个字符作为词
      if (!found) {
        index--;
        result.unshift(text.substr(index, 1));
      }
    }
    
    return result;
  }
  
  /**
   * 双向最大匹配分词算法
   * @param {string} text 要分词的文本
   * @returns {string[]} 分词结果数组
   */
  segment(text) {
    if (typeof text !== 'string' || text.length === 0) {
      return [];
    }
    
    const forwardResult = this.segmentForward(text);
    const backwardResult = this.segmentBackward(text);
    
    // 选择分词数量较少的结果
    if (forwardResult.length < backwardResult.length) {
      return forwardResult;
    } else if (backwardResult.length < forwardResult.length) {
      return backwardResult;
    }
    
    // 如果分词数量相同，选择单字较少的结果
    const countSingleForward = forwardResult.filter(word => word.length === 1).length;
    const countSingleBackward = backwardResult.filter(word => word.length === 1).length;
    
    return countSingleForward <= countSingleBackward ? forwardResult : backwardResult;
  }
  
  /**
   * 分词并返回带分隔符的字符串
   * @param {string} text 要分词的文本
   * @param {string} separator 分隔符，默认为空格
   * @returns {string} 分词后的字符串
   */
  segmentToString(text, separator = ' ') {
    return this.segment(text).join(separator);
  }
  
  /**
   * 统计分词结果中每个词的出现频率
   * @param {string} text 要分析的文本
   * @returns {Object} 词频统计对象
   */
  getWordFrequency(text) {
    const words = this.segment(text);
    const frequency = {};
    
    words.forEach(word => {
      if (frequency[word]) {
        frequency[word]++;
      } else {
        frequency[word] = 1;
      }
    });
    
    return frequency;
  }
}

// 导出模块，支持Node.js和浏览器环境
if (typeof module !== 'undefined' && module.exports) {
  module.exports = EnhancedWordSegmenter;
} else {
  window.EnhancedWordSegmenter = EnhancedWordSegmenter;
}
